--
-- Author: shineflag
-- Date: 2016-12-18 10:22:36
--

local json = require("json")
-- local json = require("dkjson")
require("sutils")

local head = 2 
local begin = head + 1
local proto = {crypt=false}


--协议文本
local protos = require("protos")

local function _unpack(data)
	if proto.crypt then
		info = string.decrypt(data)
	end
	return json.decode(data)
end

local function _pack(data)
	local info = json.encode(data)
	if proto.crypt then 
		info = string.encrypt(info)
	end
	return info
end

--创建一个请求的包
local function create_req(cmd,args)

	local p = protos[cmd]
	if p then
		local data = {}
		data.cmd = cmd 
		if p.req then
			local req = {}
			for key,value in pairs(p.req) do 
				if args[key] then
					req[key] = args[key]
				else
					req[key] = value
				end
			end

			data.req = req
		end

		return _pack(data)
	end

	return nil 

end

--根据参数创建一个回复包
local function create_resp(cmd,args)

	local p = protos[cmd]
	if p then
		local data = {}
		data.cmd = cmd 
		if p.resp then
			local resp = {}
			for key,value in pairs(p.resp) do 
				if args and args[key] then
					resp[key] = args[key]
				else
					resp[key] = value
				end
			end

			data.resp = resp
		end

		return _pack(data)
	end

	return nil 
end

--根据参数创建一个server主动推送的包
local function create_push(cmd,args)

	local p = protos[cmd]
	if p then
		local data = {}
		data.cmd = cmd 
		if p.broadcast then
			local push = {}
			for key,value in pairs(p.broadcast) do 
				if args and args[key] then
					push[key] = args[key]
				else
					push[key] = value
				end
			end

			data.broadcast = push
		end

		return _pack(data)
	end

	return nil 
end





proto.create_req = create_req
proto.create_resp = create_resp 
proto.create_push = create_push
proto.unpack = _unpack 
proto.unpack_body = _unpack
proto.pack = _pack
proto.protos = protos
return proto